import {
    createSlice
} from "@reduxjs/toolkit";
import {
    useSelector
} from "react-redux";
import {getInfo, postLogin, postLogOut} from "@/api/auth";


const authSlice = createSlice({
    name: 'auth',
    initialState: {
        token: localStorage.getItem('token'),
        info: localStorage.info ? JSON.parse(localStorage.getItem('info') as string) : {}
    },
    reducers: {
        //清空状态
        clearState(state, {payload}) {
            localStorage.clear();
            state.info = {};
            state.token = null;
        },
        upInfo(state, {payload}) {
            localStorage.setItem("info",JSON.stringify(payload))
            state.info = payload;
            //state.info = localStorage.info = JSON.stringify(payload) //这样写不行，因为state.info要接收一个对象，而不是字符串
        },
        upToken(state,{payload}) {
            state.token = localStorage.token = payload;
        }
    }
})
const {upToken, upInfo ,clearState} = authSlice.actions;
export const useSelectAuth = () => useSelector((state:any) => state.auth)//暴露状态
// 用户登录
export const postLoginAsync1 = (values:any) => {
    return async (dispatch:any) => {
        const result = await postLogin(values)
        // dispatch(upToken(result.data.token))
        dispatch(upToken(result.data))
        return result;
    }
}
//获取用户信息
export const getInfoAsync = () => {
    return async (dispatch:any, getState:any) => {
        const state = getState();
        if (state.auth.info.name) { // 如果auth中已有值，就不用重复发送axios的get请求，因此还专门用localstorage，存了info的值，并在初始状态中进行判断
            return;
        }
        const result = await getInfo();
        console.log(result,'----')
        dispatch(upInfo({
            avatar: result.data.avatar,
            name: result.data.name
        }))
    }
}
//退出登录
export const postLogOutAsync = () => {
    return async (dispatch: any) => {
        await postLogOut();
        dispatch(clearState(null))
    }
}
export default authSlice.reducer;